<template>
  <el-form ref="deptForm" :model="form" :rules="ruleForm" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getRmployeeSimple } from '@/api/employee'
import { addDepartments, getDepartmentDetail, updateDepartmentDetail } from '@/api/departments'
export default {
  props: {
    curId: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 定义部门校验函数
    const validCode = (rule, value, callBack) => {
      // value:当前表单项值
      // callBack：回调函数，验证失败==》callBack（new Error(描述错误)）  验证成功===》callBack()放行
      // 验证value在整个部门数据中是否存在,存在==？验证失败，不存在验证成功
      // 构建存在的code的数组列表
      let exitCodeList = this.originList.map(item => item.code)
      // 如果是编辑部门，将当前部门编码从列表移除
      if (this.isEdit) {
        // this.originList.filter(item => item.id !== this.curId)返回id不等于当前curId的数据
        exitCodeList = this.originList.filter(item => item.id !== this.curId).map(item => item.code)
      }
      exitCodeList.includes(value) ? callBack(new Error('部门编码' + value + '已存在')) : callBack()
    }
    // 部门名称规则校验
    const validName = (rule, value, callBack) => {
      // 筛选出同部门的
      let exitNameList = this.originList.filter(item => item.pid === this.curId).map(item => item.name)
      // 当编辑时
      if (this.isEdit) {
        // 找到当前编辑部门的对象
        const currentEditObj = this.originList.find(item => item.id === this.curId)
        console.log(this.originList, 'this.originList')
        // 编辑对象的pid
        const pid = currentEditObj.pid
        // 筛选出当前部门除了自己的部门名称列表
        exitNameList = this.originList.filter(item => item.pid === pid && item.id !== this.curId).map(item => item.name)
      }
      exitNameList.includes(value) ? callBack(new Error(value + '已存在')) : callBack()
    }
    return {
      form: {
        name: '',
        code: '',
        manger: '',
        introduce: ''
      }, ruleForm: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { pattern: /^\S{2,10}$/, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 30, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      employees: []
    }
  },
  // watch: {
  //   // 解决编辑表单数据不更新的问题
  //   curId(newval, oldval) {
  //     console.log(newval, oldval, 'qqqqqqqqq')
  //     this.loadDepartmentDetail()
  //   }
  // },
  created() {
    this.loadEmployees()
    if (this.isEdit) {
      this.loadDepartmentDetail()
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    async loadEmployees() {
      try {
        const res = await getRmployeeSimple()
        console.log(res.data, '获取简易列表')
        this.employees = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门
    async  doAdd() {
      try {
        // 还差pid，要添加
        const res = await addDepartments({ pid: this.curId, ...this.form })
        console.log(res, '新增子部门')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门信息
    async   loadDepartmentDetail() {
      try {
        const res = await getDepartmentDetail(this.curId)
        // console.log('111')
        console.log(res, 'getDepartmentDetail')
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 修改部门信息
    async doEdit() {
      try {
        const res = await updateDepartmentDetail(this.form)
        console.log(res, 'updateDepartmentDetail')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 提交
    hSubmit() {
      // 兜底检验
      this.$refs.deptForm.validate(valid => {
        if (!valid) {
          return // 校验失败
        }
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('doClose')
    }
  }
}
</script>

<style>

</style>
